<?php
/* Captcha 
	Class by infoxp
*/

	class Captcha {
		private $table=array(),$m_n1,$m_n2;
		
		const INVALID_CODE = 0;
		const VALID_CODE = 1;
		
		public function __construct($max_n1=99,$max_n2=99){	
			$this->setMaxN1($max_n1)
				 ->setMaxN2($max_n2);
				if(!isset($_SESSION["captcha_content"]))
				$_SESSION["captcha_content"] = 0;
		}
		
		public function generate(){
			$n1 = mt_rand(1,$this->MaxN1());
			$n2 = mt_rand(1,$this->MaxN2());
			$g_table = $this->Table(mt_rand(0,count($this->Table())-1));
			$_SESSION["captcha_content"] = $this->calcul($n1,$n2,$g_table);
				
			if($g_table != "-")
				return $n1 . " " . $g_table . " " . $n2;
			else{
			//inversion pour la soustration
				if($n>$n2)
					return $n1 . " " . $g_table . " " . $n2;
				else
					return $n2 . " " . $g_table . " " . $n1;
			}
		}
		
		public function checking($result){
			if(!isset($_SESSION["captcha_content"]) || $_SESSION["captcha_content"] != intval($result))
				return self::INVALID_CODE;
				
				return self::VALID_CODE;
		}
		
		private function calcul($n1,$n2,$table){
			if($table == "+")
				return $n1 + $n2;
			elseif($table == "-"){
				if($n1>$n2)
					return $n1 - $n2;
				else
					return $n2 - $n1;
			}
			elseif($table == "*")
				return $n1 * $n2;
			elseif($table == "/")
				return $n1 / $n2;
			elseif($table == "%")
				return $n1 % $n2;
			else
				$this->calcul($n1,$n2,"+");
			
		}
		
		public function setMaxN1($max_n1){
			$this->m_n1 = $max_n1;
			return $this;
		}
		
		public function MaxN1(){
			return $this->m_n1;	
		}
		
		public function setMaxN2($max_n2){
			$this->m_n2 = $max_n2;
			return $this;
		}
		
		public function MaxN2(){
			return $this->m_n2;	
		}
		
		public function setTable(Array $table){
			foreach($table as $value)
				$this->table[count($this->Table())] = $value;
				
			return $this;
		}
		
		public function Table($key=""){
			return ($key!=="") ? $this->table[$key] : $this->table;	
		}
		
	}

?>